import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: uni.getStorageSync('token') || '',
    token_type: uni.getStorageSync('token_type') || 'bearer',
    open_id: uni.getStorageSync('open_id') || '',
    union_id: uni.getStorageSync('union_id') || '',
    userInfo: uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : null
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    // Full token with type for API requests
    authHeader: (state) => state.token ? `${state.token_type} ${state.token}` : ''
  },
  
  actions: {
    setAuthData(authData) {
      // Set token and related auth data
      this.token = authData.access_token || ''
      this.token_type = authData.token_type || 'bearer'
      this.open_id = authData.open_id || ''
      this.union_id = authData.union_id || ''
      
      // Store in local storage
      uni.setStorageSync('token', this.token)
      uni.setStorageSync('token_type', this.token_type)
      uni.setStorageSync('open_id', this.open_id)
      uni.setStorageSync('union_id', this.union_id)
    },
    
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      uni.setStorageSync('userInfo', JSON.stringify(userInfo))
    },
    
    logout() {
      this.token = ''
      this.token_type = 'bearer'
      this.open_id = ''
      this.union_id = ''
      this.userInfo = null
      
      uni.removeStorageSync('token')
      uni.removeStorageSync('token_type')
      uni.removeStorageSync('open_id')
      uni.removeStorageSync('union_id')
      uni.removeStorageSync('userInfo')
    }
  }
})
